package com.sojoys.artifact.third.activemq;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import com.sojoys.artifact.third.rpc.util.SerializationUtil;


/**
 * @author : DengYing
 * @CreateDate : 2017年4月26日 下午3:53:47
 * @Description ：ActiveMQ 传输序列化 & 反序列化 (采用的protostuff序列化)
 */
public class ActiveMQMessageConverter implements MessageConverter {

	@Override
	public Object fromMessage(Message message) throws JMSException, MessageConversionException {
		if (message instanceof BytesMessage) {
			BytesMessage bytesMessage = (BytesMessage) message;
			try {
				byte[] b = new byte[(int) bytesMessage.getBodyLength()];
				while (bytesMessage.readBytes(b) != -1) { 
					return SerializationUtil.deserialize(b, ActiveMQRequest.class);
				}
			} catch (Exception e) {

			}
		}
		return null;
	}

	@Override
	public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
		if (object instanceof ActiveMQRequest) {
			BytesMessage msg = session.createBytesMessage();
			msg.writeBytes(SerializationUtil.serialize(object));
			return msg;
		}
		return null;
	}

}
